<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>09_HXR-Ajax网络请求的工具</title>
</head>

<body>

  <script>

    function creatAjax({
      method = 'GET',
      url = '',
      header = {},
      timeout = 5000,
      data = {},
    } = {}) {

      const xhr = new XMLHttpRequest()

      const promise = new Promise((resolve, reject) => {
        // 指定json格式
        xhr.responseType = 'json'
        xhr.timeout = timeout

        if (method.toUpperCase() === 'GET') {
          const params = Object.keys(data).map(key => `${key}=${data[key]}`).join('&')
          xhr.open(method, url + '?' + params, true)
          setHeader()
          xhr.send()
        } else {
          xhr.open(method, url)
          setHeader()
          xhr.send(JSON.stringify(data))
        }

        // onload监听数据加载完成
        xhr.onload = function () {
          // http状态码判断请求是否成功
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(xhr.response)
          } else {
            reject({ status: xhr.status, message: xhr.statusText })
          }
        }

        function setHeader() {
          if (JSON.stringify(header) !== '{}') {
            Object.keys(header).forEach(key => {
              xhr.setRequestHeader(key, header[key])
            })
          } else {
            xhr.setRequestHeader("Content-type", "application/json")
          }
        }
      })

      promise.xhr = xhr

      return promise
    }

    const pAjax = creatAjax({
      url: "http://123.207.32.32:1888/02_param/get",
      method: "GET",
      data: {
        name: "XMLHttpRequest",
        age: 18
      },
    })

    pAjax.then(response => {
      console.log("response", response);
    }).catch(error => {
      console.log("error", error);
    })

  </script>

</body>

</html>

  </script>

</body>

</html>